package com.wbq501.common.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import com.noober.background.BackgroundLibrary
import java.lang.reflect.ParameterizedType

abstract class BaseFragment<VM : ViewModel, DB : ViewDataBinding> : Fragment(){
    val TAG = javaClass.name

    lateinit var mViewModel: VM
    lateinit var mDatabind: DB

    private var dataBindView : View? = null
    abstract fun initView()
    abstract fun initData()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        initDataBind()
        initView()
        initData()
        return dataBindView
    }

    /**
     * 创建DataBinding
     */
    private fun initDataBind() {
        //利用反射 根据泛型得到 ViewDataBinding
        val superClass = javaClass.genericSuperclass
        val aClass = (superClass as ParameterizedType).actualTypeArguments[1] as Class<*>
        BackgroundLibrary.inject(context)
        val method = aClass.getDeclaredMethod("inflate", LayoutInflater::class.java)
        mDatabind =  method.invoke(null,layoutInflater) as DB
        dataBindView = mDatabind.root
        mDatabind.lifecycleOwner = this
    }
}